/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import  MultiFormatReader  from './core/MultiFormatReader.js';
import  DecodeHintType  from './core/DecodeHintType.js';
import  RGBLuminanceSource  from './core/RGBLuminanceSource.js';
import  BinaryBitmap  from './core/BinaryBitmap.js';
import  HybridBinarizer  from './core/HybridBinarizer.js';
import  EAN13Reader  from './core/oned/EAN13Reader.js';
import  Code128Reader  from './core/oned/Code128Reader.js';

//https://github.com/zxing-js/library

export { decode, decodeEAN_13, decodeCODE_128 };

function decodeCODE_128(luminances, width, height) {
  const reader = new Code128Reader();
  const luminanceSource = new RGBLuminanceSource(luminances, width, height);
  const binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

  try {
    let result = reader.decode(binaryBitmap);
    let rawBytes = result.getRawBytes().toString();
    let text = result.getText();
    return text;
  } catch (err) {
    let error = `decode error ${err}`
    print(error)
    return error
  }
}

function decodeEAN_13(luminances, width, height) {
  const reader = new EAN13Reader();
  const luminanceSource = new RGBLuminanceSource(luminances, width, height);
  const binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

  let result = reader.decode(binaryBitmap);
  let text = result.getText();
  return text;
}


function decode(luminances, width, height, format) {
  const hints = new Map();
  const formats = [format];

  hints.set(DecodeHintType.POSSIBLE_FORMATS, formats);

  const reader = new MultiFormatReader();

  reader.setHints(hints);

  const luminanceSource = new RGBLuminanceSource(luminances, width, height);
  const binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

  try {
    let result = reader.decode(binaryBitmap);
    let text = result.getText();
    return text;
  } catch (err) {
    let error = `decode error ${err}`
    print(error)
    return error
  }
}